package com.zst.dollars.handler.codec.decoder;

import com.alibaba.fastjson.JSONObject;
import com.zst.dollars.entity.Message;
import com.zst.dollars.entity.MessageType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 把ByteBuf转换为Message的解码器
 */
public class ByteToMessageDecoder extends MessageToMessageDecoder<ByteBuf> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(msg.toString(StandardCharsets.UTF_8));
        int messageType = jsonObject.getInteger("messageType");
        Message message = JSONObject.parseObject(msg.toString(StandardCharsets.UTF_8), MessageType.getClazzByType(messageType));
        out.add(message);
    }
}
